<?php

if (!defined('IN_IA')) {
	exit('Access Denied');
}

class User_EweiShopV2Page extends PluginWebPage
{
	public function main()
	{
		global $_W;
		global $_GPC;
		$pindex = max(1, intval($_GPC['page']));
		$psize = 20;
		$params = array(':uniacid' => $_W['uniacid']);
		$condition = '';
		$keyword = trim($_GPC['keyword']);

		if (!empty($keyword)) {
			$condition .= ' and ( name like :keyword or shop_user_grade like :keyword or distribution_grade like :keyword)';
			$params[':keyword'] = '%' . $keyword . '%';
		}

		$status = empty($_GPC['status']) ? '' : intval($_GPC['status']);
		switch ($status) {
			case '1'://已审核，使用中
				$condition .= ' and status = 1 ';
				break;
			case '2'://待审核
				$condition .= ' and status = 0 ';
				break;
			case '3'://已过期
				$condition .= ' and ( status = 2 OR end_time < ' . time() . ' )';
				break;
			default:
				$condition .= '';
				break;
		}

		$sql = 'select * from ' . tablename('ewei_shop_identity') . ' where uniacid=:uniacid ' . $condition . ' ORDER BY levelnum ASC';

		if (empty($_GPC['export'])) {
			$sql .= ' limit ' . (($pindex - 1) * $psize) . ',' . $psize;
		}

		$list = pdo_fetchall($sql, $params);
		$total = pdo_fetchcolumn('select count(*) from' . tablename('ewei_shop_identity') . ' where uniacid = :uniacid ' . $condition, $params);

		// 会员等级
		$member_level = pdo_fetchall('SELECT * FROM ' . tablename('ewei_shop_member_level') . ' WHERE uniacid = :uniacid', array(':uniacid' => $_W['uniacid']));
		foreach ($member_level as $key => $value) {
			$user[$value['id']] = $value;
		}


		// 分销等级
		$commission = pdo_fetchall('SELECT * FROM ' . tablename('ewei_shop_commission_level') . ' WHERE uniacid = :uniacid', array(':uniacid' => $_W['uniacid']));
		foreach ($commission as $key => $value) {
			$distribution[$value['id']] = $value;
		}

		foreach ($list as $key => $value) {
			if($value['levelnum'] != '0'){
				$list[$key]['end_time'] = date('Y-m-d', $value['end_time']);
			}
			
			$list[$key]['url'] = mobileUrl('identity/order',array('goods_id' => $value['buy_goods_id']), true);

			// 会员等级
			foreach ($user as $k => $val) {
				if($val['id'] == $value['shop_user_grade_id'] && $val['enabled'] == 0){
					$list[$key]['shop_user_grade'] = $value['shop_user_grade'].'(未启用)';
				}
				if($val['id'] == $value['end_shop_user_grade_id'] && $val['enabled'] == 0){
					$list[$key]['end_shop_user_grade'] = $value['end_shop_user_grade'].'(未启用)';
				}
			}
		}


		$pager = pagination2($total, $pindex, $psize);
		load()->func('tpl');
		include $this->template();
	}

	public function qrcode(){
		global $_W;
		global $_GPC;
		$goods_id = $_GPC['goods_id'];

		if(!empty($goods_id)){
			$url = mobileUrl('identity/order',array('goods_id' => $goods_id), true);
			$res['qrcode'] = $this->createVoucherQrcode($url, $_W['uniacid'].$goods_id);
			$res['code'] = '1';
		}
		

		die(json_encode($res));
	}

	public function add()
	{
		$this->post();
	}

	public function edit()
	{
		$this->post();
	}

	protected function post()
	{
		global $_W;
		global $_GPC;
		$id = intval($_GPC['id']);
		$area_set = m('util')->get_area_config_set();
		$new_area = intval($area_set['new_area']);

		for($i = 1; $i <= 100; $i++){
			$levelnum[$i] = $i;
		}

		$item = pdo_fetch('select * from ' . tablename('ewei_shop_identity') . ' where id=:id and uniacid=:uniacid limit 1', array(':id' => $id, ':uniacid' => $_W['uniacid']));
		$self_condition = !empty($item['self_condition']) ? unserialize($item['self_condition']) : array();
		$up_buy_condition = !empty($item['up_buy_condition']) ? unserialize($item['up_buy_condition']) : array();

		$setting = pdo_fetch('SELECT * FROM ' . tablename('ewei_shop_identity_setting') . ' WHERE uniacid = :uniacid', array('uniacid' => $_W['uniacid']));

		$goods = pdo_fetch('SELECT id,title FROM ' . tablename('ewei_shop_goods') . ' WHERE uniacid = :uniacid AND id = :id', array(':uniacid' => $_W['uniacid'], ':id' => $item['buy_goods_id']));

		// 身份等级
		$identity = pdo_fetchall('SELECT id,name FROM ' . tablename('ewei_shop_identity') . ' WHERE uniacid = :uniacid AND status = 1', array('uniacid' => $_W['uniacid']));

		// 会员等级
		$member_level = pdo_fetchall('SELECT * FROM ' . tablename('ewei_shop_member_level') . ' WHERE uniacid = :uniacid', array(':uniacid' => $_W['uniacid']));
		foreach ($member_level as $key => $value) {
			$user[$value['id']] = $value;
		}


		// 分销等级
		$commission = pdo_fetchall('SELECT * FROM ' . tablename('ewei_shop_commission_level') . ' WHERE uniacid = :uniacid', array(':uniacid' => $_W['uniacid']));
		foreach ($commission as $key => $value) {
			$distribution[$value['id']] = $value;
		}
		
		// 门店等级
		$mendian = pdo_fetchall('SELECT * FROM ' . tablename('ewei_shop_mendian_level') . ' WHERE uniacid = :uniacid ORDER BY levelnum ASC', array(':uniacid' => $_W['uniacid']));
		foreach ($mendian as $key => $value) {
			$mendian_level[$value['id']] = $value;
		}

		// 多商户分组
		$merch = pdo_fetchall('SELECT * FROM ' . tablename('ewei_shop_merch_group') . ' WHERE uniacid = :uniacid', array(':uniacid' => $_W['uniacid']));
		foreach ($merch as $key => $value) {
			$merch_level[$value['id']] = $value;
		}

		// 全民股东等级
		$globonus = pdo_fetchall('SELECT * FROM ' . tablename('ewei_shop_globonus_level') . ' WHERE uniacid = :uniacid', array(':uniacid' => $_W['uniacid']));
		foreach ($globonus as $key => $value) {
			$globonus_level[$value['id']] = $value;
		}

		// 区域代理等级
		$abonus = pdo_fetchall('SELECT * FROM ' . tablename('ewei_shop_abonus_level') . ' WHERE uniacid = :uniacid', array(':uniacid' => $_W['uniacid']));
		foreach ($abonus as $key => $value) {
			$abonus_level[$value['id']] = $value;
		}


		// $buy_condition = explode(',', $item['condition_identity_level']);
		// 
		if(!empty($item['condition_identity_level'])){
			$buy_condition1 = pdo_fetchall('SELECT id,name,levelnum FROM ' . tablename('ewei_shop_identity') .' WHERE uniacid = :uniacid AND levelnum > 0 AND id IN ('.$item['condition_identity_level'].')', array(':uniacid' => $_W['uniacid']));
		}



		
		if ($_W['ispost']) {

			$shop_user_grade_id 	   = intval($_GPC['shop_user_grade_id']);
			$shop_user_grade 		   = $user[$shop_user_grade_id]['levelname'];//会员等级
			$end_shop_user_grade_id    = intval($_GPC['end_shop_user_grade_id']);
			$end_shop_user_grade 	   = $user[intval($_GPC['end_shop_user_grade_id'])]['levelname'];//到期会员等级
			$distribution_grade_id 	   = intval($_GPC['distribution_grade_id']);
			$distribution_grade 	   = $distribution[$distribution_grade_id]['levelname'];//分销等级
			$end_distribution_grade_id = intval($_GPC['end_distribution_grade_id']);
			$end_distribution_grade    = $distribution[$end_distribution_grade_id]['levelname'];//到期分销等级
			$start_time                = strtotime($_GPC['start_time']);
			$end_time				   = strtotime($_GPC['end_time']);
			$useful_time			   = !empty($_GPC['useful_time']) ? $_GPC['useful_time'] : $_GPC['useful_time1'];
			$self_condition			   = empty($_GPC['self_condition']) ? '' : serialize($_GPC['self_condition']);// 本身身份购买权限
			$up_buy_condition		   = empty($_GPC['up_buy_condition']) ? '' : serialize($_GPC['up_buy_condition']);// 上一级身份购买权限

			if($distribution_grade_id == '-1'){ $distribution_grade = '待审核'; }
			if($end_distribution_grade_id == '-1'){ $end_distribution_grade = '待审核'; }
			
			// 身份名是否存在
			$name = trim($_GPC['name']);
			if(!empty($name)) {
				$res = pdo_fetch('SELECT id FROM ' . tablename('ewei_shop_identity') . ' WHERE uniacid = :uniacid AND name = :name', array(':uniacid' => $_W['uniacid'], ':name' => $name));
			} else {
				show_json(0, '请输入身份名称！');
			}

			// 商品信息
			$goods_id = intval($_GPC['buy_goods_id']);
			if($_GPC['levelnum'] != 0){
				if(!empty($goods_id)) {
					$res = pdo_fetch('SELECT id,title,productprice,marketprice FROM ' . tablename('ewei_shop_goods') . ' WHERE uniacid = :uniacid AND id = :id', array(':uniacid' => $_W['uniacid'], ':id' => $goods_id));
				} else {
					show_json(0, '请选择商品！');
				}
			}

			if($_GPC['is_use_member_level'] == '1'){
				if(empty($shop_user_grade_id)) {show_json(0, '请选择会员等级！');}
			}
			if($_GPC['is_use_distribution_level'] == '1'){
				if(empty($distribution_grade_id)) {show_json(0, '请选择分销等级！');}
			}
			if($_GPC['is_use_merch'] == '1'){
				if(empty($_GPC['merch_id'])) {show_json(0, '请选择多商户分组！');}
			}
			if($_GPC['is_use_abonus_agent'] == '1'){
				if(empty($_GPC['abonus_agent_id'])) {show_json(0, '请选择区域代理等级！');}
			}
			if($_GPC['is_use_globonus_partner'] == '1'){
				if(empty($_GPC['globonus_partner_id'])) {show_json(0, '请选择全民股东等级！');}
			}
			if($_GPC['is_use_mendian'] == '1'){
				if(empty($_GPC['mendian_level_id'])) {show_json(0, '请选择门店等级！');}
			}
			if(empty($useful_time)){show_json(0, '请选择有效天数！');}

			
			// $up_buy_condition0 = $_GPC['up_buy_condition'];
			// if
			// foreach ($up_buy_condition0 as $key => $value) {
			// 	$up_buy_condition .= $value.',';
			// }
			


			$data = array(
				'uniacid' 					=> $_W['uniacid'], 
				'levelnum'					=> $_GPC['levelnum'],
				'name'						=> $name,
				'is_use_member_level'		=> $_GPC['is_use_member_level'],
				'shop_user_grade_id' 		=> $shop_user_grade_id,
				'shop_user_grade'    		=> empty($shop_user_grade) ? '默认等级' : $shop_user_grade,
				'end_shop_user_grade_id'	=> $end_shop_user_grade_id,
				'end_shop_user_grade'   	=> empty($end_shop_user_grade) ? '默认等级' : $end_shop_user_grade,
				'is_use_distribution_level' => $_GPC['is_use_distribution_level'],
				'distribution_grade_id' 	=> $distribution_grade_id,
				'distribution_grade'		=> empty($distribution_grade) ? '默认等级' : $distribution_grade,
				'end_distribution_grade_id' => $end_distribution_grade_id,
				'end_distribution_grade'	=> empty($end_distribution_grade) ? '默认等级' : $end_distribution_grade,
				'buy_goods_id'				=> $goods_id,
				'buy_goods_title'			=> $res['title'],
				'buy_goods_price'			=> $res['marketprice'],
				'is_use_merch'				=> $_GPC['is_use_merch'],
				'merch_id'					=> $_GPC['merch_id'],
				'end_merch_id'				=> $_GPC['end_merch_id'],
				'is_use_abonus_agent'		=> $_GPC['is_use_abonus_agent'],
				'abonus_agent_id'			=> $_GPC['abonus_agent_id'],
				'end_abonus_agent_id'		=> $_GPC['end_abonus_agent_id'],
				'is_use_globonus_partner'	=> $_GPC['is_use_globonus_partner'],
				'globonus_partner_id'		=> $_GPC['globonus_partner_id'],
				'end_globonus_partner_id'	=> $_GPC['end_globonus_partner_id'],
				'is_use_mendian'			=> $_GPC['is_use_mendian'],
				'mendian_level_id'			=> $_GPC['mendian_level_id'],
				'end_mendian_level_id'		=> $_GPC['end_mendian_level_id'],
				'start_time'				=> $start_time,
				'end_time'					=> $end_time,
				'useful_time'				=> $useful_time,
				'status'					=> intval($_GPC['status']),
				'grade_agreement'			=> trim($_GPC['grade_agreement']),
				'show_type'					=> intval($_GPC['show_type']),
				'remarks'					=> trim($_GPC['remarks']),
				'is_use_identity_detail'	=> intval($_GPC['is_use_identity_detail']),//是否使用身份详情
				'identity_detail'			=> $_GPC['identity_detail'],//身份详情
				'is_use_buy_num_limit'		=> intval($_GPC['buy_num_limit']),//是否启用购买数量限制
				'is_use_show_condition'		=> intval($_GPC['is_use_show_condition']),//显示条件是否使用
				'is_use_buy_condition'      => intval($_GPC['is_use_buy_condition']),//上一级购买身份
				'is_use_self_condition'     => intval($_GPC['is_use_self_condition']),//本身购买身份
				'self_condition'			=> $self_condition,
				'up_buy_condition'			=> $up_buy_condition,
			);
			
			if (empty($_GPC['id'])) {
				$data['add_time'] = time();
				pdo_insert('ewei_shop_identity', $data);
			
				$id = pdo_insertid();
				
				plog('mendian.user.add', '添加身份 ID: ' . $data['id'] . ' 名称: ' . $data['name'] . '<br/>会员等级: ' . $shop_user_grade . '<br/>到期时间: ' . date('Y-m-d', $data['accounttime']));
			}
			else {
				$data['edit_time'] = time();
				pdo_update('ewei_shop_identity', $data, array('id' => $id));
				
				plog('mendian.user.edit', '编辑身份 ID: ' . $data['id'] . ' 名称: ' . $data['name'] . ' -> ' . $data['title'] . '<br/>会员等级: ' . $item['shop_user_grade'] . ' -> ' . $data['shop_user_grade'] . '<br/>分销等级: ' . $item['distribution_grade'] . ' -> ' . $data['distribution_grade'] . '<br/>到期时间: ' . date('Y-m-d', $item['end_time']) . ' -> ' . date('Y-m-d', $data['end_time']));
			}
			show_json(1, array('url' => webUrl('identity/user', array('status' => $data['status']))));
		}

		
		
		include $this->template();
	}

	public function status()
	{
		global $_W;
		global $_GPC;
		$id = intval($_GPC['id']);

		if (empty($id)) {
			$id = (is_array($_GPC['ids']) ? implode(',', $_GPC['ids']) : 0);
		}

		$items = pdo_fetchall('SELECT id,name FROM ' . tablename('ewei_shop_identity') . ' WHERE id in( ' . $id . ' ) AND uniacid=' . $_W['uniacid']);

		foreach ($items as $item) {
			pdo_update('ewei_shop_identity', array('status' => intval($_GPC['status'])), array('id' => $item['id']));
			plog('identity.category.edit', ('修改身份状态<br/>ID: ' . $item['id'] . '<br/>身份名称: ' . $item['name'] . '<br/>状态: ' . $_GPC['status']) == 1 ? '显示' : '隐藏');
		}

		show_json(1, array('url' => referer()));
	}

	public function delete()
	{
		global $_W;
		global $_GPC;
		$id = intval($_GPC['id']);

		if (empty($id)) {
			$id = (is_array($_GPC['ids']) ? implode(',', $_GPC['ids']) : 0);
		}

		$uniacid = $_W['uniacid'];
		$items = pdo_fetchall('SELECT * FROM ' . tablename('ewei_shop_identity') . ' WHERE id in( ' . $id . ' ) AND uniacid=' . $_W['uniacid']);

		foreach ($items as $item) {
			pdo_delete('ewei_shop_identity', array('id' => $item['id'], 'uniacid' => $uniacid));
			plog('identity.user.delete', '删除`身份 <br/>身份:  ID: ' . $item['id'] . ' / 名称:   ' . $item['name'] . '<br/>会员等级： ' . $item['shop_user_grade'] . '<br/>分销等级： ' . $item['distribution_grade']);
		}

		show_json(1);
	}

	// 身份启用记录
	public function ploglist() {
		global $_W;
		global $_GPC;
		$pindex = max(1, intval($_GPC['page']));
		$psize = 20;
		$params = array(':uniacid' => $_W['uniacid']);
		$condition = '';
		$keyword = trim($_GPC['keyword']);

		if (!empty($keyword)) {
			$condition .= ' and ( m.nickname like :keyword or im.idnetity like :keyword)';
			$params[':keyword'] = '%' . $keyword . '%';
		}

		$status = empty($_GPC['status']) ? '' : intval($_GPC['status']);
		switch ($status) {
			case '1'://已启用
				$condition .= ' and p.status = 1 ';
				break;
			case '2'://已停用
				$condition .= ' and p.status = 2 ';
				break;
			case '3'://已恢复
				$condition .= ' and p.status = 3 ';
				break;
			default:
				$condition .= '';
				break;
		}

		/*$identity_member = pdo_fetchall('SELECT shop_user_id FROM ' . tablename('ewei_shop_identity_member') . ' WHERE uniacid = :uniacid', array(':uniacid' => $_W['uniacid']));
		foreach ($identity_member as $key => $value) {
			$identity_uid .= $value['shop_user_id'].',';
		}
		$condition .= ' AND p.uid in ('.trim($identity_uid, ',').')';*/

		$sql = 'select p.*,m.nickname,m.avatar,im.identity from ' . tablename('ewei_shop_identity_plog') . ' p LEFT JOIN ' . tablename('ewei_shop_member') . ' m ON m.uid = p.uid LEFT JOIN ' . tablename('ewei_shop_identity_member') . ' im ON im.id = p.identity_id where p.uniacid=:uniacid ' . $condition . ' ORDER BY p.add_time DESC';

		if (empty($_GPC['export'])) {
			$sql .= ' limit ' . (($pindex - 1) * $psize) . ',' . $psize;
		}

		$list = pdo_fetchall($sql, $params);
		$total = pdo_fetchcolumn('select count(*) from' . tablename('ewei_shop_identity_plog') . ' p LEFT JOIN ' . tablename('ewei_shop_member') . ' m ON m.uid = p.uid LEFT JOIN ' . tablename('ewei_shop_identity_member') . ' im ON im.id = p.identity_id where p.uniacid=:uniacid ' . $condition, $params);

		$status = array('1' => '已启用', '2' => '已停用', '3' => '已恢复');
		foreach ($list as $key => $value) {
			$list[$key]['add_time'] = date('Y-m-d', $value['add_time']);
			$list[$key]['end_time'] = date('Y-m-d', $value['end_time']);
			$list[$key]['status'] = $status[$value['status']];
			if(empty($value['old_identity'])) $list[$key]['old_identity'] = '无';
		}

		$pager = pagination2($total, $pindex, $psize);
		load()->func('tpl');
		include $this->template();

	}

	// 刷新身份
	public function renew() {
		global $_W;
		global $_GPC;
		$id = intval($_GPC['id']);

		if (empty($id)) {
			$id = (is_array($_GPC['ids']) ? implode(',', $_GPC['ids']) : 0);
		}

		$items = pdo_fetchall('SELECT * FROM ' . tablename('ewei_shop_identity_member') . ' WHERE id in( ' . $id . ' ) AND uniacid=' . $_W['uniacid']);
		$idnetity = pdo_fetchall('SELECT * FROM ' . tablename('ewei_shop_identity') . ' WHERE uniacid = :uniacid AND status = 1', array(':uniacid' => $_W['uniacid']));

		foreach ($items as $key => $item) {
			$member = pdo_fetch('SELECT openid,uid FROM ' . tablename('ewei_shop_member'). ' WHERE uniacid = :uniacid AND uid = :uid', array(':uniacid' => $_W['uniacid'], ':uid' => $item['shop_user_id']));
			if($item['end_time'] < time() && !empty($item['end_time'])){

				foreach ($idnetity as $key => $value) {
					if(empty($item['identity_id'])) {$item['identity_id'] = '7';}
					if($value['id'] == $item['identity_id']){
						$info = array(
							'status' 					=> 2,
							'identity'					=> '',
							'identity_id'				=> '',
							'shop_user_grade_id' 		=> $value['end_shop_user_grade_id'],
							'shop_user_grade'	 		=> $value['end_shop_user_grade'],
							'end_shop_user_grade_id' 	=> '',
							'end_shop_user_grade'	 	=> '',
							'distribution_grade_id' 	=> $value['end_distribution_grade_id'],
							'distribution_grade'		=> $value['end_distribution_grade'],
							'end_distribution_grade_id' => '',
							'end_distribution_grade'	=> '',
							'merch_id'					=> $value['end_merch_id'],
							'end_merch_id'				=> '',
							'abonus_agent_id'			=> $value['end_abonus_agent_id'],
							'end_abonus_agent_id'		=> '',
							'globonus_partner_id'		=> $value['end_globonus_partner_id'],
							'end_globonus_partner_id'	=> '',
							'mendian_level_id'			=> $value['end_mendian_id'],
							'end_mendian_level_id'		=> '',
						);

						pdo_update('ewei_shop_identity_member', $info, array('id' => $item['id']));
						
						plog('identity.member.edit', ('修改会员身份状态<br/>ID: ' . $item['id'] . '<br/>会员名称: ' . $item['user_name'] . '<br/>状态: ' . $_GPC['status']) == 1 ? '显示' : '到期');

						// pdo_update('ewei_shop_mendian_info', array('status' => 0), array('uid' => $item['shop_user_id'], 'uniacid' => $_W['uniacid']));


						$data = array(
							'uniacid' => $_W['uniacid'], 
							'uid' => $item['uid'], 
							'status' => 3, 
							'content' => '用户'.$item['user_name'].'身份到期', 
							'add_time' => time(), 
							'old_identity' => $item['identity'], 
							'old_identity_id' => $item['identity_id'], 
						);
						pdo_insert('ewei_shop_identity_plog', $data);


						// 用户表修改 ewei_shop_member
						$mdata = array(
							'level' 		=> $value['end_shop_user_grade_id'], 
						);
						if($value['end_distribution_grade_id'] == '-1'){//分销商
							$mdata['agentlevel'] = $value['distribution_grade_id'];
							$mdata['status']     = 0;
						}else{
							$mdata['agentlevel'] = $value['end_distribution_grade_id'];
						}
						if($value['globonus_partner_id'] == '-1'){ //股东
							$mdata['agentlevel'] 	= $value['globonus_partner_id'];
							$mdata['partnerstatus'] = 0;
						}else{
							$mdata['agentlevel'] = $value['globonus_partner_id'];
						}
						if($value['abonus_agent_id'] == '-1'){//区域代理
							$mdata['agentlevel'] 	= $value['abonus_agent_id'];
							$mdata['aagentstatus']  = 0;
						}else{
							$mdata['agentlevel'] = $value['abonus_agent_id'];
						}
						pdo_update('ewei_shop_member', $mdata, array('uniacid' => $_W['uniacid'], 'uid' => $member['uid']));
						// 多商户用户表 ewei_shop_merch_user
						if($value['end_mendian_level_id'] == '-1'){
							$mudata['groupid'] = $value['merch_id'];
							$mudata['status']  = 0;
						}else{
							$mudata['groupid'] = $value['end_merch_id'];
						}
						pdo_update('ewei_shop_merch_user', $mudata, array('uniacid' => $_W['uniacid'], 'openid' => $member['openid']));
						// 门店用户表 ewei_shop_mendian_info
						if($value['end_mendian_level_id'] == '-1'){
							$mddata['mendian_level'] = $value['mendian_level_id'];
							$mddata['status']        = 0;
							$set = pdo_fetch('SELECT * FROM ' . tablename('ewei_shop_mendian_level') . ' WHERE uniacid = :uniacid AND id = :id', array(':uniacid' => $_W['uniacid'], ':id' => $value['mendian_level_id']));
						}else{
							$mddata['mendian_level'] = $value['end_mendian_level_id'];
							$set = pdo_fetch('SELECT * FROM ' . tablename('ewei_shop_mendian_level') . ' WHERE uniacid = :uniacid AND id = :id', array(':uniacid' => $_W['uniacid'], ':id' => $value['end_mendian_level_id']));
						}
						$mendian = pdo_fetch('SELECT * FROM ' . tablename('ewei_shop_mendian_info'). ' WHERE uniacid = :uniacid AND uid = :uid', array(':uniacid' => $_W['uniacid'], ':uid' => $member['uid']));
						$mdset = array(
							'uniacid'			=> $_W['uniacid'],
							'is_show_diy_menu'  => $set['is_show_diy_menu'],
							'is_show_mobile'	=> $set['is_show_mobile'],
							'is_show_message'	=> $set['is_show_message'],
							'is_show_wechat'	=> $set['is_show_wechat'],
							'is_show_remarks'	=> $set['is_show_remarks'],
							'is_show_address'	=> $set['is_show_address'],
							'remarks'			=> $set['remarks'],
							'status'			=> 0,
							'is_show_type'		=> $set['is_show_type'],
						);
						$mendian = pdo_fetch('SELECT * FROM ' . tablename('ewei_shop_mendian_info'). ' WHERE uniacid = :uniacid AND uid = :uid', array(':uniacid' => $_W['uniacid'], ':uid' => $member['uid']));
						if(empty($mendian)){
							pdo_insert('ewei_shop_mendian_info', $mddata);
							$mendian_id = pdo_insertid();
							$mdset['mendian_id'] = $mendian_id;
							pdo_insert('ewei_shop_mendian_setting', $mdset);
						}else{
							pdo_update('ewei_shop_mendian_info', $mddata, array('uniacid' => $_W['uniacid'], 'uid' => $member['uid']));
							$setting = pdo_fetch('SELECT * FROM '.tablename('ewei_shop_mendian_setting').' WHERE uniacid = :uniacid AND mendian_id = :mendian_id', array(':uniacid' => $_W['uniacid'], ':mendian_id' => $mendian['id']));
							if(empty($setting))
							{
								$mdset['mendian_id'] = $mendian['id'];
								pdo_insert('ewei_shop_mendian_setting', $mdset);
							} else {
								pdo_update('ewei_shop_mendian_setting', $mdset, array('uniacid' => $_W['uniacid'], 'mendian_id' => $mendian['id']));
							}
						}
					}
				}
			} else {

				foreach ($idnetity as $key => $value) {
					if($value['id'] == $item['identity_id']){

						$info = array(
							'status' 					=> 1,
							'is_use_member_level'		=> $value['is_use_member_level'],
							'shop_user_grade_id' 		=> $value['shop_user_grade_id'],
							'shop_user_grade'	 		=> $value['shop_user_grade'],
							'end_shop_user_grade_id' 	=> $value['end_shop_user_grade_id'],
							'end_shop_user_grade'	 	=> $value['end_shop_user_grade'],
							'is_use_distribution_level' => $value['is_use_distribution_level'],
							'distribution_grade_id' 	=> $value['distribution_grade_id'],
							'distribution_grade'		=> $value['distribution_grade'],
							'end_distribution_grade_id' => $value['end_distribution_grade_id'],
							'end_distribution_grade'	=> $value['end_distribution_grade'],
							'is_use_merch'				=> $value['is_use_merch'],
							'merch_id'					=> $value['merch_id'],
							'end_merch_id'				=> $value['end_merch_id'],
							'is_use_abonus_agent'		=> $value['is_use_abonus_agent'],
							'abonus_agent_id'			=> $value['abonus_agent_id'],
							'end_abonus_agent_id'		=> $value['end_abonus_agent_id'],
							'is_use_globonus_partner'	=> $value['is_use_globonus_partner'],
							'globonus_partner_id'		=> $value['globonus_partner_id'],
							'end_globonus_partner_id'	=> $value['end_globonus_partner_id'],
							'is_use_mendian'			=> $value['is_use_mendian'],
							'mendian_level_id'			=> $value['mendian_level_id'],
							'end_mendian_level_id'		=> $value['end_mendian_level_id'],
						);
						pdo_update('ewei_shop_identity_member', $info, array('id' => $item['id']));
						
						plog('identity.member.edit', ('修改会员身份状态<br/>ID: ' . $item['id'] . '<br/>会员名称: ' . $item['user_name'] . '<br/>状态: ' . $_GPC['status']) == 1 ? '显示' : '到期');

						// 用户表修改 ewei_shop_member
						$mdata = array(
							'level' 		=> $value['shop_user_grade_id'], 
							'agentlevel' 	=> $value['distribution_grade_id'], //分销商
							'status'		=> 0,
							'partnerlevel' 	=> $value['globonus_partner_id'], //股东
							'partnerstatus' => 0,
							'aagentlevel' 	=> $value['abonus_agent_id'],//区域代理
							'aagentstatus'	=> 0,
						);
						
						pdo_update('ewei_shop_member', $mdata, array('uniacid' => $_W['uniacid'], 'uid' => $member['uid']));
						// 多商户用户表 ewei_shop_merch_user
						$mudata = array(
							'groupid' => $value['merch_id'],
							'openid' => $member['openid'],
							'status' => 0,
						);
						$merch = pdo_fetch('SELECT * FROM ' . tablename('ewei_shop_merch_user') . ' WHERE uniacid = :uniacid AND openid = :openid', array(':uniacid' => $_W['uniacid'], ':openid' => $member['openid']));
						if($value['is_use_merch'] == 1){						
							if(empty($merch)){
								pdo_insert('ewei_shop_merch_user', $mudata);
							} else {
								pdo_update('ewei_shop_merch_user', $mudata, array('uniacid' => $_W['uniacid'], 'openid' => $member['openid']));
							}
						}
						// 门店用户表 ewei_shop_mendian_info
						$mddata = array(
							'mendian_level' => $value['mendian_level_id'],
							'status' => 0,
						);
						$set = pdo_fetch('SELECT * FROM ' . tablename('ewei_shop_mendian_level') . ' WHERE uniacid = :uniacid AND id = :id', array(':uniacid' => $_W['uniacid'], ':id' => $value['mendian_level_id']));
						$mendian = pdo_fetch('SELECT * FROM ' . tablename('ewei_shop_mendian_info'). ' WHERE uniacid = :uniacid AND uid = :uid', array(':uniacid' => $_W['uniacid'], ':uid' => $member['uid']));
						$mdset = array(
							'uniacid'			=> $_W['uniacid'],
							'is_show_diy_menu'  => $set['is_show_diy_menu'],
							'is_show_mobile'	=> $set['is_show_mobile'],
							'is_show_message'	=> $set['is_show_message'],
							'is_show_wechat'	=> $set['is_show_wechat'],
							'is_show_remarks'	=> $set['is_show_remarks'],
							'is_show_address'	=> $set['is_show_address'],
							'remarks'			=> $set['remarks'],
							'status'			=> 0,
							'is_show_type'		=> $set['is_show_type'],
						);
						if($value['is_use_mendian'] == 1){
							if(empty($mendian)){
								pdo_insert('ewei_shop_mendian_info', $mddata);
								$mendian_id = pdo_insertid();
								$mdset['mendian_id'] = $mendian_id;
								pdo_insert('ewei_shop_mendian_setting', $mdset);
							}else{
								pdo_update('ewei_shop_mendian_info', $mddata, array('uniacid' => $_W['uniacid'], 'uid' => $member['uid']));
								$setting = pdo_fetch('SELECT * FROM '.tablename('ewei_shop_mendian_setting').' WHERE uniacid = :uniacid AND mendian_id = :mendian_id', array(':uniacid' => $_W['uniacid'], ':mendian_id' => $mendian['id']));
								if(empty($setting))
								{
									$mdset['mendian_id'] = $mendian['id'];
									pdo_insert('ewei_shop_mendian_setting', $mdset);
								} else {
									pdo_update('ewei_shop_mendian_setting', $mdset, array('uniacid' => $_W['uniacid'], 'mendian_id' => $mendian['id']));
								}
							}
						}
						
					}
				}
			}
		}

		show_json(1);

	}

	// 二维码生成及上传
	public function createVoucherQrcode($url,$filename) 
	{
		global $_W;
		global $_GPC;

		$path = ATTACHMENT_ROOT . 'images/' . $_W['uniacid'] . '/' . date('Y',time()) . '/' . date('m',time()) . '/';
		$localpath = IA_ROOT . '/addons/ewei_shopv2/data/qrcode/' . $_W['uniacid'] . '/';
		if (!(is_dir($path))) 
		{
			load()->func('file');
			mkdirs($path);
		}
		$file = $filename . '.jpg';
		$path1 = '../images/' . $_W['uniacid'] . '/' . date('Y',time()) . '/' . date('m',time()) . '/' . $file;
		$path2 = 'images/' . $_W['uniacid'] . '/' . date('Y',time()) . '/' . date('m',time()) . '/' . $file;
		$qrcode_file = $path . $file;
		$local_qrcode_file = $localpath.$file;
		if (!(is_file($qrcode_file))) 
		{
			require_once(__DIR__.'/phpqrcode.php');
			// require_once IA_ROOT . '/framework/library/qrcode/phpqrcode.php';
			QRcode::png($url, $qrcode_file, QR_ECLEVEL_L, 4);
			QRcode::png($url, $local_qrcode_file, QR_ECLEVEL_L, 4);
		}
		$remotestatus = $this->file_remote_upload($path2);

		// unlink($local_qrcode_file);
		return tomedia($path2);
	}
	// 文件上传
	function file_remote_upload($filename, $auto_delete_local = true) {
		global $_W;

		if (empty($_W['setting']['remote']['type'])) {
			return false;
		}

		if ($_W['setting']['remote']['type'] == '1') {
			// require_once(IA_ROOT . '/framework/library/ftp/ftp.php');
			require_once(__DIR__.'/ftp.php');
			$ftp_config = array(
				'hostname' => $_W['setting']['remote']['ftp']['host'],
				'username' => $_W['setting']['remote']['ftp']['username'],
				'password' => $_W['setting']['remote']['ftp']['password'],
				'port' => $_W['setting']['remote']['ftp']['port'],
				'ssl' => $_W['setting']['remote']['ftp']['ssl'],
				'passive' => $_W['setting']['remote']['ftp']['pasv'],
				'timeout' => $_W['setting']['remote']['ftp']['timeout'],
				'rootdir' => $_W['setting']['remote']['ftp']['dir'],
			);
			
			$ftp = new Ftp($ftp_config);
			if (true === $ftp->connect()) {
				$response = $ftp->upload(ATTACHMENT_ROOT . '/' . $filename, $filename);
				if ($auto_delete_local) {
					$this->file_delete($filename);
				}
				if (!empty($response)) {
					return true;
				} else {
					return error(1, '远程附件上传失败，请检查配置并重新上传');
				}
			} else {
				return error(1, '远程附件上传失败，请检查配置并重新上传');
			}
		} elseif ($_W['setting']['remote']['type'] == '2') {
			// require_once(IA_ROOT.'/framework/library/alioss/autoload.php');
			require_once(__DIR__.'/alioss/src/OSS/OssClient.php');
			load()->model('attachment');
			$buckets = attachment_alioss_buctkets($_W['setting']['remote']['alioss']['key'], $_W['setting']['remote']['alioss']['secret']);
			$endpoint = 'http://'.$buckets[$_W['setting']['remote']['alioss']['bucket']]['location'].'.aliyuncs.com';
			try {
				$ossClient = new \OSS\OssClient($_W['setting']['remote']['alioss']['key'], $_W['setting']['remote']['alioss']['secret'], $endpoint);
				$ossClient->uploadFile($_W['setting']['remote']['alioss']['bucket'], $filename, ATTACHMENT_ROOT.$filename);
			} catch (\OSS\Core\OssException $e) {
				return error(1, $e->getMessage());
			}
			if ($auto_delete_local) {
				$this->file_delete($filename);
			}
			return true;
		}elseif ($_W['setting']['remote']['type'] == '3') {
			// require_once(IA_ROOT . '/framework/library/qiniu/autoload.php');
			require_once(__DIR__.'/qiniu/src/Qiniu/functions.php');
			require_once(__DIR__.'/qiniu/src/Qiniu/Config.php');
			require_once(__DIR__.'/qiniu/src/Qiniu/Storage/UploadManager.php');
			$auth = new Qiniu\Auth($_W['setting']['remote']['qiniu']['accesskey'],$_W['setting']['remote']['qiniu']['secretkey']);
			$config = new Qiniu\Config();
			$uploadmgr = new Qiniu\Storage\UploadManager($config);
					$putpolicy = Qiniu\base64_urlSafeEncode(json_encode(array('scope' => $_W['setting']['remote']['qiniu']['bucket'].':'. $filename)));
			$uploadtoken = $auth->uploadToken($_W['setting']['remote']['qiniu']['bucket'], $filename, 3600, $putpolicy);
			list($ret, $err) = $uploadmgr->putFile($uploadtoken, $filename, ATTACHMENT_ROOT. '/'.$filename);
			if ($auto_delete_local) {
				$this->file_delete($filename);
			}
			if ($err !== null) {
				return error(1, '远程附件上传失败，请检查配置并重新上传');
			} else {
				return true;
			}
		} elseif ($_W['setting']['remote']['type'] == '4') {
			if (!empty($_W['setting']['remote']['cos']['local'])) {
				// require(IA_ROOT.'/framework/library/cosv4.2/include.php');
				require_once(__DIR__.'/cosv4.2/include.php');
				qcloudcos\Cosapi :: setRegion($_W['setting']['remote']['cos']['local']);
				$uploadRet = qcloudcos\Cosapi::upload($_W['setting']['remote']['cos']['bucket'], ATTACHMENT_ROOT .$filename,'/'.$filename,'',3 * 1024 * 1024, 0);
			} else {
				// require(IA_ROOT.'/framework/library/cos/include.php');
				require_once(__DIR__.'cos/Qcloud_cos/Cosapi.php');
				$uploadRet = \Qcloud_cos\Cosapi::upload($_W['setting']['remote']['cos']['bucket'], ATTACHMENT_ROOT .$filename,'/'.$filename,'',3 * 1024 * 1024, 0);
			}
			if ($uploadRet['code'] != 0) {
				switch ($uploadRet['code']) {
					case -62:
						$message = '输入的appid有误';
						break;
					case -79:
						$message = '输入的SecretID有误';
						break;
					case -97:
						$message = '输入的SecretKEY有误';
						break;
					case -166:
						$message = '输入的bucket有误';
						break;
				}
				return error(-1, $message);
			}
			if ($auto_delete_local) {
				$this->file_delete($filename);
			}
		}
	}
	function file_delete($file) {
		if (empty($file)) {
			return FALSE;
		}
		if (file_exists($file)) {
			@unlink($file);
		}
		if (file_exists(ATTACHMENT_ROOT . '/' . $file)) {
			@unlink(ATTACHMENT_ROOT . '/' . $file);
		}
		return TRUE;
	}

}

?>
